//
//  FunctionServiceTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/28.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "FunctionServiceTabVC.h"
#import "SubjectRecommendModel.h"
#import "ServiceModel.h"
#import "ServiceCell.h"
#import "FunctionServiceHeadVC.h"
@interface FunctionServiceTabVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) NSInteger page;
@property(nonatomic,assign) NSInteger row;
@property(nonatomic,strong) NSMutableArray *serviceArray;
@property(nonatomic,strong) FunctionServiceHeadVC *headView;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,assign) NSInteger type;
@property(nonatomic,assign) NSInteger order;
@property(nonatomic,strong) NSString *industry;
@property(nonatomic,strong) NSString *address;
@end
static NSString *identifierService = @"ServiceCell";
@implementation FunctionServiceTabVC
-(UITableView *)tableView
{
    if (!_tableView) {
        XLog(@"self.navHeight:%ld",(long)self.navHeight);
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), kVWidth, kVHeight-CGRectGetMaxY(self.headView.frame)-self.navHeight-44) style:UITableViewStylePlain];
        self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
-(NSMutableArray *)serviceArray
{
    if (!_serviceArray) {
        _serviceArray = [NSMutableArray array];
        
    }
    return _serviceArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
     self.manager = [AFHTTPSessionManager manager];
   self.headView = [[FunctionServiceHeadVC alloc]initWithFrame:CGRectMake(0, 0, kUIScreen.size.width, 60)];
    XLog(@"self.height:%ld",(long)self.height);
    self.headView.kNavHeight = self.navHeight;
    [self.view addSubview:self.headView];
    [self.view addSubview:self.tableView];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceCell" bundle:nil] forCellReuseIdentifier:identifierService];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(associationindexSearch:) name:@"associationindexSearch" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(functionIndustry:) name:@"functionIndustry" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serviceFunctionSearchType:) name:@"serviceFunctionSearchType" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serviceFunctionSearchAddress:) name:@"serviceFunctionSearchAddress" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serviceFunctionSearchOrder:) name:@"serviceFunctionSearchOrder" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];

}
-(void)refresh
{
    self.page = 1;
    self.row = 10;
    self.serviceArray = nil;
    [self reloadInternetData];
}
-(void)reloadMore
{
    self.page ++;
    [self reloadInternetData];

}

- (void)setSubjectModel:(SubjectRecommendModel *)subjectModel
{
    
    _subjectModel = subjectModel;
    
}
#pragma mark-代理:网络请求失败
-(void)qingqiusibai:(NSNotification *)info
{
    [self.tableView.mj_header endRefreshing];
}
-(void)reloadInternetData
{
    NSString *rows = [NSString stringWithFormat:@"%ld",self.row];
    NSString *pages = [NSString stringWithFormat:@"%ld",self.page];
    self.dict = @{
                    @"page":pages,
                    @"rows":rows,
                    @"param":self.subjectModel.title
                    };
    XLog(@"self.dict:%@",self.dict);
      [CustomeManager POSTWithURLIndex:19 parameters:self.dict success:^(NSDictionary *dict) {

      } failure:^(NSError *error) {

      }];
}
-(void)associationindexSearch:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    if (date.count) {
        for (NSDictionary *dict in date) {
            ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
            [self.serviceArray addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }else {
        self.tableView.emptyDataSetSource = self;
        self.tableView.emptyDataSetDelegate = self;
    }
    if (self.serviceArray.count) {
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
        self.tableView.mj_footer = footer;
                [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                footer.stateLabel.font = [UIFont systemFontOfSize:12];
                footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
        if (!date.count) {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
    }
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
    [WSProgressHUD dismiss];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
#pragma mark-通知:行业
-(void)functionIndustry:(NSNotification *)info
{
    self.page = 1;
    self.serviceArray = nil;
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    self.industry = [dict objectForKey:@"industry"];
    XLog(@"self.industry:%@",self.industry);
    [self reloadInternetSubData];
    
}
#pragma mark-通知:类型
-(void)serviceFunctionSearchType:(NSNotification *)info
{
    self.page = 1;
    self.serviceArray = nil;
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    self.type = [[dict objectForKey:@"type"] integerValue];
    [self reloadInternetSubData];
}
#pragma mark-代理:地区
-(void)serviceFunctionSearchAddress:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    self.address = [dict objectForKey:@"address"];
    if ([self.address isEqualToString:@"全国不限"]) {
        self.address = @"";
    }
    self.page = 1;
    self.serviceArray = nil;
    [self reloadInternetSubData];
}
#pragma mark-代理:排序
-(void)serviceFunctionSearchOrder:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    self.order = [[dict objectForKey:@"order"] integerValue];
    self.page = 1;
    self.serviceArray = nil;
    [self reloadInternetSubData];
}
-(void)reloadInternetSubData
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    NSString *types = [NSString stringWithFormat:@"%ld",self.type];
    NSString *orders = [NSString stringWithFormat:@"%ld",self.order];
    NSString *pages = [NSString stringWithFormat:@"%ld",self.page];
    NSString *rows = [NSString stringWithFormat:@"%ld",self.row];
    self.dict = @{
                  @"uid":@"",
                  @"associationtype":self.subjectModel.title,
                  @"associationtypesub1":@"",
                  @"associationtypesub2":@"",
                  @"commonindustry":@"",
                  @"industry":self.industry,
                  @"type":types,
                  @"order":orders,
                  @"page":pages,
                  @"rows":rows,
                  @"address":self.address
                  };
    XLog(@"self.dict:%@",self.dict);
    
    self.urlString =[NSString stringWithFormat:@"%@/association/search",kUrl];
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSArray *date = [responseObject objectForKey:@"date"];
        if (date.count) {
            for (NSDictionary *dict in date) {
                ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                [self.serviceArray addObject:model];
            }
            [self.tableView.mj_header endRefreshing];
//            [self.tableView.mj_footer endRefreshing];
            
        }else {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
        if (!self.serviceArray.count) {
            [self.tableView.mj_footer removeFromSuperview];
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
        }
        [self.tableView reloadData];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WSProgressHUD dismiss];
    }];

}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.serviceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    ServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierService forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ServiceModel *model = self.serviceArray[indexPath.row];
    cell.serviceModel = model;
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 144;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ServiceModel *model = self.serviceArray[indexPath.row];
//    if ([self.delegate respondsToSelector:@selector(functionServiceTabVC:withIndexPath:withModel:)]) {
//        [self.delegate functionServiceTabVC:self withIndexPath:indexPath withModel:model];
//    }
    if (self.returnValueBlock) {
        self.returnValueBlock(model);
    };
}
@end
